package com.gsit.expenditure.controller;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import javax.validation.Validation;
import javax.validation.Validator;
import org.apache.commons.lang3.StringUtils;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import com.gsit.expenditure.client.domina.InvoiceBean;
import com.gsit.expenditure.domain.Bill;
import com.gsit.expenditure.domain.Invoice;
import com.gsit.expenditure.services.InvoiceService;
import com.gsit.expenditure.utils.AppContextLoader;
import com.gsit.expenditure.utils.InvoiceStatus;
import com.gsit.expenditure.utils.Utils;
import eu.schudt.javafx.controls.calendar.DatePicker;

public class SearchInvoiceController extends BaseController implements Initializable {
		
	@FXML private HBox dateHBox1;
	private DatePicker fromDate;
	
	@FXML private HBox dateHBox2;
	private DatePicker toDate;
	
	@FXML private TextField invoiceNumberText;
	@FXML private TextField customerText;
	@FXML private TextField vehicleText;
	//@FXML private TextField vendorText;
	@FXML private ComboBox<InvoiceStatus> stateList; 
	
	// for populating data in table
	@FXML private TableView<InvoiceBean> searchInvoiceTable;
	@FXML private TableColumn<InvoiceBean, String> invoiceNoColumn;
	@FXML private TableColumn<InvoiceBean, String> createdDateColumn;
	@FXML private TableColumn<InvoiceBean, String> customerNameColumn;
	@FXML private TableColumn<InvoiceBean, String> statusColumn;

	
	//ERROR LABEL
	@FXML private Label searchInvoiceError;

	
	private List<Invoice> invoicesList;
	private final ObservableList<InvoiceBean> observableList = FXCollections.observableArrayList();;
	
	private Validator validator;
	private InvoiceService invoiceService;
	private InvoiceBean invoiceBean;
	Set<Bill> bill ;
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		invoiceService = AppContextLoader.getBean(InvoiceService.class);
		invoiceBean = new InvoiceBean(null);
		StringBuffer path = Utils.getPreviewPath();
		//Table Columns
		invoiceNoColumn.setCellValueFactory(new PropertyValueFactory<InvoiceBean, String>("invoiceNumber"));
		createdDateColumn.setCellValueFactory(new PropertyValueFactory<InvoiceBean, String>("createdDate"));
		customerNameColumn.setCellValueFactory(new PropertyValueFactory<InvoiceBean, String>("customerName"));
		statusColumn.setCellValueFactory(new PropertyValueFactory<InvoiceBean, String>("status"));
	
		//FOR DATE
		dateHBox1.getChildren();
		fromDate = new DatePicker(Locale.ENGLISH);
		fromDate.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		fromDate.getCalendarView().todayButtonTextProperty().set("Today");
		fromDate.getCalendarView().setShowWeeks(false);
		fromDate.getStylesheets().add("css/datepicker/DatePicker.css");
		// Add DatePicker to grid
		dateHBox1.getChildren().add(fromDate);
		
		dateHBox2.getChildren();
		toDate = new DatePicker(Locale.ENGLISH);
		toDate.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		toDate.getCalendarView().todayButtonTextProperty().set("Today");
		toDate.getCalendarView().setShowWeeks(false);
		toDate.getStylesheets().add("css/datepicker/DatePicker.css");
		// Add DatePicker to grid
		dateHBox2.getChildren().add(toDate);
		
		stateList.getItems().addAll(InvoiceStatus.values());
		
		searchInvoiceTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
		StringBuffer path = Utils.getDestinationPath();
			
			@Override
				public void handle(MouseEvent event) {
					if (event.getButton().equals(MouseButton.PRIMARY)) {
						if (event.getClickCount() == 2) {
							InvoiceBean invoiceBean = searchInvoiceTable.getSelectionModel().getSelectedItem();
							Invoice invoice = invoiceBean.getInvoice();
							String fileLocation = invoice.getInvoiceStorage().getFileLocation();
							
							try {
									Desktop.getDesktop().open(new File(fileLocation));
									System.out.println("**********FILE OPENED*********");
								} catch (IOException e) {
									e.printStackTrace();
									
								invoiceBean.reLoad(invoiceBean.getInvoice());
							}
						}
					}
				}
			});
		}

	@Override
	public void onSearch() {
		
		System.out.println("onSearch()--Invoice....");
		String customerNameOrId = customerText.getText();
		String vehicle = vehicleText.getText();
		//String vendor = vendorText.getText();
		InvoiceStatus invoiceStatus = stateList.getSelectionModel().getSelectedItem();

		Invoice invoice1 = invoiceBean.getObject();
		if (isValidate(invoice1)) {
			Date selectedFromDate = fromDate.getSelectedDate();
			Date selectedToDate = toDate.getSelectedDate();
			String invoiceNumber=invoiceNumberText.getText();

		Invoice invoice = new Invoice();
		invoice.setInvoiceNumber(invoiceNumber);
		System.out.println("invoiceStatus :: "+invoiceStatus);
		if(invoiceStatus == null){
			invoiceStatus = invoiceStatus.UNPAID ;
		}
		invoice.setStatus(invoiceStatus);
		
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
		if(StringUtils.isBlank(invoice.getInvoiceNumber()) && StringUtils.isBlank(customerNameOrId) && StringUtils.isBlank(vehicle)
			 && selectedFromDate == null && selectedFromDate== null && invoiceStatus == null ){
			System.out.println("inside  if invoice  :: " + invoice);
			invoicesList = invoiceService.findAll();
			for (Invoice invoice2 : invoicesList) {
				System.out.println(" for :: "+invoice2);
			}
			
		}
		else{
			
			String fromDateString = "" ; 
			String toDateString = "" ;
			if(selectedFromDate!= null){
				 fromDateString = dateFormat.format(selectedFromDate);
			}if(selectedToDate!= null){
				 toDateString = dateFormat.format(selectedToDate);
			}
			
			System.out.println("inside  else invoice  :: " + invoice);
		  invoicesList = invoiceService.findInvoices( invoice, fromDateString, toDateString, customerNameOrId, vehicle);
		    for (Invoice invoice2 : invoicesList) {
				System.out.println(" for :: "+invoice2);
			}
		}
			
			onLoad();
		}
	}

	
	
	
	@Override
	public void onLoad() {
		
	if (invoicesList != null) {
			searchInvoiceTable.getItems().clear();
			observableList.clear();
			List<InvoiceBean> invoiceBeans = new ArrayList<>();
			for (Invoice invoice : invoicesList) {
				InvoiceBean invoiceBean = new InvoiceBean(invoice);
				invoiceBeans.add(invoiceBean);
			}
			
			observableList.addAll(invoiceBeans);
			searchInvoiceTable.setItems(observableList);
		}
	}
	
	public Boolean isValidate(Invoice invoice) {
		clearAllErrorLabels();
		Boolean result = Boolean.TRUE;
		if (validator == null) {
			validator = Validation.buildDefaultValidatorFactory()
					.getValidator();
		}
		invoice.setCreatedDate(fromDate.getSelectedDate());
		invoice.setModifiedDate(toDate.getSelectedDate());

		if (fromDate.getSelectedDate() != null) {
			if (fromDate.getSelectedDate().after(new java.util.Date())) {
				searchInvoiceError.setText("Should not be future date");
			}
		}
		if (toDate.getSelectedDate() != null) {
			if (toDate.getSelectedDate().after(new java.util.Date())) {
				searchInvoiceError.setText("Should not be future date");
			}
		}
		return result;
	}

	private void clearAllErrorLabels() {
		searchInvoiceError.setText("");
	}
	

}
